package rensoft.android.rpc;

import java.util.concurrent.atomic.AtomicBoolean;

import static rensoft.android.lang.AndroidLang.sleep;
import static rensoft.java.lang.Lang.iterate;
import static rensoft.java.lang.Lang.list;

import android.os.Handler;
import android.os.Looper;
import rensoft.java.collections.List;
import rensoft.java.lang.Run;

public class RequestManager {

  protected Handler threadHandler;
  private final AtomicBoolean isHandlerReady = new AtomicBoolean(false);
  private final List<Run> waitingRequests = list();

  public RequestManager() {
    new Thread() {
      @Override
      public void run() {
        startThreadHandler();
      };
    }.start();
  }

  public void postAtFrontOfQueue(IServerRequest request) {
    threadHandler.postAtFrontOfQueue(request);
  }

  public void send(final Run request) {
    if (isHandlerReady.get())
      threadHandler.post(request);
    else waitingRequests.add(request);
  }

  private void startThreadHandler() {
    Looper.prepare();
    threadHandler = new Handler();
    isHandlerReady.set(true);
    sleep(50);
    for (final Run request : iterate(waitingRequests).reverse())
      threadHandler.postAtFrontOfQueue(request);
    Looper.loop();
  }
}
